<script setup>
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router';
import { useDebounceFn } from '@vueuse/core'
import { getAssetsFiles } from '@/utils'
import { fetchSignInData, fetchSignInReward } from '@/api/signIn';
import { useUserStore } from '@/store'
import { useWaitUserLoadFn } from '@/hooks'

import { SignInInsert } from '/public/adConfig.js'

import BiPopup from '@/components/biPopup/index.vue'
import Ad from '@/components/ad/index.vue'


defineOptions({
    name: 'BiSignin'
})

const props = defineProps({
    type: {
        type: String,
        default: 'normal'
    }
})

const router = useRouter()

const userStore = useUserStore()

const loading = ref(true)

const signInday = ref(0)
const signInState = ref(false)
const signInPointsMap = ref([])

const filterSignInPoints = computed(() => {
    if (signInPointsMap.value.length > 0) {
        const newbieSignInPoint = signInPointsMap.value[1] // 首次签到显示的第一天奖励
        const oldStagerSignInPoint = signInPointsMap.value[2] // 非首次签到显示的第一天奖励
        const normalSignInPoint = signInPointsMap.value.slice(3)
        normalSignInPoint.unshift(userStore.firstSign ? newbieSignInPoint : oldStagerSignInPoint)
        return normalSignInPoint
    }
    return []
})

function handleFetchSignInData() {
    fetchSignInData({ device: userStore.uuid }).then(res => {
        signInday.value = res.data.data.signDays
        signInState.value = res.data.data.todaySign
        signInPointsMap.value = res.data.data.rewardSignVOS
        userStore.$patch({
            signInday: res.data.data.signDays,
            signInState: res.data.data.todaySign
        })
        loading.value = false
    }).catch(err => {
        throw new Error(err)
    })
}
useWaitUserLoadFn(handleFetchSignInData)

function handleSetImgOpacity(day) {
    if (signInday.value >= day) {
        return { opacity: '0.5' }
    }
}

const currencyType = {
    1: getAssetsFiles('coin.png'),
    2: getAssetsFiles('cash.png')
}
function handleSetTimelineIcon(type) {
    return currencyType[type]
}

const timelineWidth = computed(() => {
    return { '--width': `${(signInday.value / 7) * 100}%` }
})
const handleSetGreetFont = (day) => {
    if (signInday.value >= day) {
        return {
            color: '#f2456b'
        }
    }
}

function useTimelineText(i) {
    return i == 1 ? 'Today' : `Day ${i}`
}

const signInBtnText = computed(() => signInState.value ? 'Get more' : 'Check-in')

const showSignInRewardPopup = ref(false)
function openSignSuccessPopup() {
    showSignInRewardPopup.value = true
}
function closeSignSuccessPopup() {
    showSignInRewardPopup.value = false
}

const signInReward = ref({})
const handleCheckMoreAd = useDebounceFn(() => {
    loading.value = true
    fetchSignInReward({ device: userStore.uuid }).then(res => {
        if (res.data.code === 0) {
            // uploadTaskEventToAdmin({
            //     device: userStore.device,
            //     moduleType: 2,
            //     eventType: 32
            // })
            signInReward.value = res.data.data
            handleFetchSignInData()
            openSignSuccessPopup()
            loading.value = false
        }
    }).catch(err => {
        loading.value = false
        throw new Error(err)
    })
}, 500)

const rewardsType = computed(() => {
    const noCoin = signInReward.value.coins == 0 || !signInReward.value.coins
    const noCash = signInReward.value.cash == 0 || !signInReward.value.cash
    if (signInReward.value.coins > 0 && noCash) {
        return 'coin'
    }

    if (noCoin && signInReward.value.cash > 0) {
        return 'cash'
    }

    if (signInReward.value.coins > 0 && signInReward.value.cash > 0) {
        return 'all'
    }
})
const signInRewardPopupProps = computed(() => ({
    rewardsType: rewardsType.value,
    rewardsNum: signInReward.value.coins > 0 ? signInReward.value.coins : signInReward.value.cash,
    coinNum: signInReward.value.coins,
    cashNum: signInReward.value.cash
}))

const showSignInAds = ref(false)
function handleOpenSigninAds() {
    showSignInAds.value = true
}

function handleSignInFn() {
    const fn = signInState.value ? handleToEggOrTurntable : handleOpenSigninAds
    fn()
}

const hasLotteryCount = computed(() => {
    return userStore.turntableCount < 30
})
const hasEggCount = computed(() => {
    return userStore.eggCount < 30
})
function handleToEggOrTurntable() {
    closeSignSuccessPopup()
    if (!hasEggCount.value && !hasLotteryCount.value) {
        router.push({
            path: '/egg'
        })
        return
    }

    if (hasEggCount.value) {
        router.push({
            path: '/egg'
        })
        return
    }

    if (hasLotteryCount.value) {
        router.push({
            path: '/turntable'
        })
        return
    }
}
</script>

<template>
    <div class="sign">
        <div class="sign-title">Check-In Streak: 0{{ signInday }} Day(s)</div>
        <ul>
            <li>
                <div class="timeline">
                    <div class="timeline-list">
                        <div class="timeline-list-item" v-for="(item, key) in filterSignInPoints">
                            <div class="timeline-list-item-icon">
                                <img :style="handleSetImgOpacity(key + 1)" :src="handleSetTimelineIcon(item.currency)"
                                    width="25">
                            </div>
                            <span>+{{ item.amount }}</span>
                        </div>
                    </div>
                    <div class="timeline_line" :style="timelineWidth">
                        <div class="timeline_line__dot" v-for="item in 7" :key="item"></div>
                    </div>
                    <div class="timeline_date">
                        <span :style="handleSetGreetFont(key + 1)" v-for="(item, key) in 7" :key="item">
                            {{ useTimelineText(key + 1) }}
                        </span>
                    </div>
                </div>
            </li>
            <li>
                <div class="sign-button click-ad" v-if="loading">
                    <van-loading color="#ffffff" size="20" />
                </div>
                <div class="sign-button click-ad" v-else @click="handleSignInFn">
                    <span>{{ signInBtnText }}</span>
                </div>
            </li>
        </ul>
    </div>

    <Teleport to="#app">
        <van-popup v-model:show="showSignInAds" :close-on-click-overlay="false" :close-on-popstate="true"
            :closeable="true" :style="{ background: 'transparent' }" @close="handleCheckMoreAd">
            <div style="width: 90vmin;height: 80vh;display: flex;align-items: center;background-color: #fff;">
                <KeepAlive>
                    <!-- <Ad v-if="showSignInAds" :path="SignInInsert.path" :id="SignInInsert.id" :size="[300, 250]" /> -->
                </KeepAlive>
            </div>
        </van-popup>
    </Teleport>

    <Teleport to="#app">
        <BiPopup v-model:show="showSignInRewardPopup" v-bind="signInRewardPopupProps" @click="handleToEggOrTurntable">
        </BiPopup>
    </Teleport>
</template>

<style scoped lang="scss">
@import url(./index.scss);
</style>